package com.q.tqb.activity.send;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.v7.widget.AppCompatSpinner;
import android.text.TextUtils;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.baidu.mapapi.model.LatLng;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.jakewharton.rxbinding2.widget.TextViewTextChangeEvent;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.q.tqb.R;
import com.q.tqb.activity.grab.GrabMapActivity;
import com.q.tqb.adapter.MySpinnerAdapter;
import com.q.tqb.base.AppConst;
import com.q.tqb.base.BaseActivity;
import com.q.tqb.luban.Luban;
import com.q.tqb.luban.OnCompressListener;
import com.q.tqb.model.BalanceInfo;
import com.q.tqb.model.Packet_numInfo;
import com.q.tqb.model.SpinnerInfo;
import com.q.tqb.model.WxPayData;
import com.q.tqb.util.FileUtil;
import com.q.tqb.util.LogUtil;
import com.q.tqb.util.SPUtil;
import com.q.tqb.util.StringUtil;
import com.q.tqb.util.http.IRawResponse;
import com.q.tqb.util.http.IResponse;
import com.q.tqb.util.http.OkHttpUtil;
import com.q.tqb.util.oss.OssCallback;
import com.q.tqb.util.oss.OssService;
import com.q.tqb.view.GlideLoader;
import com.q.tqb.view.dialog.PayDialog;
import com.q.tqb.view.dialog.PayPassDialog;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;


/**
 * @author Administrator
 *         发送地图红包
 */
public class SendMapActivity extends BaseActivity implements  AdapterView.OnItemSelectedListener{


    @BindView(R.id.et_money)
    EditText mEtMoney;
    @BindView(R.id.et_reward_money)
    EditText mEtRewardMoney;
    @BindView(R.id.et_amount)
    EditText mEtAmount;
    @BindView(R.id.et_content)
    EditText mEtContent;
    @BindView(R.id.map_view)
    ImageView mMapView;
    @BindView(R.id.rb_store)
    RadioButton mRbStore;
    @BindView(R.id.rg_type)
    RadioGroup mRgType;
    @BindView(R.id.rb_person)
    RadioButton mRbPerson;
    @BindView(R.id.bt_send)
    Button mBtSend;
    @BindView(R.id.iv_up)
    ImageView ivUp;

    @BindView(R.id.spinner)
    AppCompatSpinner spinner;

    private LatLng curLatLng;
    private String address;

    private int uid;

    private int payType;
    private String myMoney;
    private String orderId;
    private String payPass;
    private PayDialog payDialog;

    private MyBroadcastReceiver mBroadcastReceiver;


    private String path;
    private String upPointName;

    private MySpinnerAdapter spinnerAdapter;
    /**
     * 当前选中
     */
    private SpinnerInfo spinnerInfo;
    /**
     * 服务端返回的红包个数信息
     */
    private Packet_numInfo info;

    @Override
    public int getLayoutId() {
        return R.layout.activity_send_map;
    }

    @Override
    public void init(Bundle savedInstanceState) {
        uid = (int) SPUtil.get(this, "uid", 0);

        setTitle("发地图红包");
        mEtMoney.requestFocus();

        getMoney();

        initReceiver();

        initImagePicker();

        mEtAmount.setEnabled(false);
        spinnerAdapter = new MySpinnerAdapter(this);
        spinner.setOnItemSelectedListener(this);
        getBankArea();

        final int INTERVAL = 800; //输入时间间隔为300毫秒

        RxTextView.textChangeEvents(mEtMoney)
                .debounce(INTERVAL, TimeUnit.MILLISECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<TextViewTextChangeEvent>() {


                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(TextViewTextChangeEvent textViewTextChangeEvent) {
                        getPacketNum();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }

    private void initReceiver() {
        mBroadcastReceiver = new MyBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(AppConst.PAY_MAP);
        registerReceiver(mBroadcastReceiver, intentFilter);
    }

    private void initImagePicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new GlideLoader());
        imagePicker.setShowCamera(true);
        imagePicker.setCrop(false);
        imagePicker.setSaveRectangle(true);
        imagePicker.setSelectLimit(1);
    }

    @OnClick({R.id.iv_back, R.id.bt_send, R.id.map_view, R.id.iv_up})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.map_view:
                Intent intent = new Intent(SendMapActivity.this, SelectMapLocationActivity.class);
                startActivityForResult(intent, 50);
                break;
            case R.id.bt_send:
                sendMapRed();
                break;
            case R.id.iv_up:
                selectDialog();
                break;
            default:
                break;
        }
    }

    private void selectDialog() {
        final String[] items = {"相机拍照", "相册选择"};
        AlertDialog.Builder singleChoiceDialog = new AlertDialog.Builder(SendMapActivity.this);
        singleChoiceDialog.setTitle("选择方式");
        // 第二个参数是默认选项，此处设置为0
        singleChoiceDialog.setSingleChoiceItems(items, 0,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {

                            ImagePicker.getInstance().setSelectLimit(1);
                            Intent intent = new Intent(SendMapActivity.this, ImageGridActivity.class);
                            // 是否是直接打开相机
                            intent.putExtra(ImageGridActivity.EXTRAS_TAKE_PICKERS, true);
                            startActivityForResult(intent, 100);
                        } else {
                            ImagePicker.getInstance().setSelectLimit(1);

                            Intent intent1 = new Intent(SendMapActivity.this, ImageGridActivity.class);
                                /* 如果需要进入选择的时候显示已经选中的图片，
                                 * 详情请查看ImagePickerActivity
                                 * */
//                                intent1.putExtra(ImageGridActivity.EXTRAS_IMAGES,images);
                            startActivityForResult(intent1, 100);
                        }
                        dialog.dismiss();
                    }
                });
        singleChoiceDialog.show();
    }

    private void sendMapRed() {
        String packetMoney = mEtMoney.getText().toString();
        String packetAmount = mEtAmount.getText().toString();
        String packetTitle = mEtContent.getText().toString();
        if (TextUtils.isEmpty(address)) {
            showToast("请选择地址");
            return;
        }
        if (TextUtils.isEmpty(path)) {
            showToast("请选择图片");
            return;
        }
        if (TextUtils.isEmpty(packetMoney) || TextUtils.isEmpty(packetAmount) || TextUtils.isEmpty(packetTitle)) {
            showToast("请完整红包信息");
            return;
        }
        upImage(path);
    }

    private void upImage(String localPath) {
        mProgressDialog.show();
        String comPath = Environment.getExternalStorageDirectory() + "/tqb/tqb_1.jpg";
        Luban.with(this)
                // 传人要压缩的图片列表
                .load(localPath)
                // 忽略不压缩图片的大小
                .ignoreBy(-10)
                .setTargetDir(comPath)
                //设置回调
                .setCompressListener(new OnCompressListener() {
                    @Override
                    public void onStart() {
                    }

                    @Override
                    public void onSuccess(File file) {
                        upPointName = "image/" + uid + "_" + System.currentTimeMillis() + ".JPEG";
                        OssService.asyncPutFile(upPointName, file.getAbsolutePath(), new OssCallback(new Handler(), new IRawResponse() {
                            @Override
                            public void onSuccess(String response) {
                                mProgressDialog.dismiss();
                                sendMapImgRed();
                            }

                            @Override
                            public void onFailure(String errorMsg) {
                                showToast("请检查您的网络");
                                LogUtil.i(errorMsg);
                            }
                        }));
                    }

                    @Override
                    public void onError(Throwable e) {
                        // TODO 当压缩过程出现问题时调用
                    }
                }).launch();    //启动压缩
    }

    private void sendMapImgRed() {
        String packetMoney = mEtMoney.getText().toString();
        final double allMoney = Double.valueOf(packetMoney);
        payDialog = new PayDialog(SendMapActivity.this, allMoney, myMoney);
        payDialog.setOnSettingListener(new PayDialog.CommonListener() {
            @Override
            public void onClick(int type) {
                if (type == 1) {
                    payType = 3;
                    PayPassDialog payPassDialog = new PayPassDialog(SendMapActivity.this, allMoney, 1);
                    payPassDialog.show();
                    showInputMethod();
                    payPassDialog.setOnSettingListener(new PayPassDialog.CommonListener() {
                        @Override
                        public void onClick(String pass) {
                            payPass = pass;
                            payOrder();
                        }
                    });

                } else {
                    payType = 2;
                    payOrder();
                }
            }
        });
        payDialog.show();
    }


    private void showInputMethod() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }, 100);
    }

    private void payOrder() {

        String packetMoney = mEtMoney.getText().toString();
        String packetAmount = mEtAmount.getText().toString();
        String packetTitle = mEtContent.getText().toString();
        String getSecret = mEtContent.getText().toString();


        Map<String, String> map = new HashMap<>();
        map.put("uid", uid + "");
        map.put("packet_money", packetMoney);
        map.put("reward_money", "0");
        map.put("packet_num", packetAmount);
        map.put("packet_title", packetTitle);
        map.put("get_secret", getSecret);
        map.put("packet_address", address);
        map.put("packet_type", "3");
        AppConst.ORDER_TYPE = 3;
        map.put("longitude", curLatLng.longitude + "");
        map.put("latitude", curLatLng.latitude + "");
        map.put("pay_type", payType + "");
        if (payType == 3) {
            map.put("pay_password", payPass);
        }
        map.put("packet_picture", AppConst.OSS_URL + upPointName);
        map.put("is_show_list", "1");

        map.put("packet_level", spinnerInfo.level);
        map.put("reward_money", "0");

        LogUtil.i(map.toString());
        mProgressDialog.show();
        OkHttpUtil.getInstance().post(this, AppConst.URL_SEND_PACKET, map, new IResponse() {
            @Override
            public void onSuccess(JsonElement element) {
                LogUtil.i(element.toString());
                mProgressDialog.dismiss();
                try {
                    JSONObject jsonObject = new JSONObject(element.toString());
                    orderId = jsonObject.getString("order_id");
                    if (payType == 3) {
                        showToast("红包发送成功！");
                        finish();
                    } else if (payType == 2) {
                        wxPay();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, String errorMsg) {
                showToast(errorMsg);
                mProgressDialog.dismiss();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBroadcastReceiver);
    }

    private void wxPay() {
        Map<String, String> map = new HashMap<>();
        map.put("order_id", orderId);
        LogUtil.i(map.toString());
        mProgressDialog.show();
        OkHttpUtil.getInstance().post(this, AppConst.URL_WX_PAY, map, new IResponse() {
            @Override
            public void onSuccess(JsonElement element) {
                mProgressDialog.dismiss();
                LogUtil.i(element.toString());
                Gson gson = new Gson();
                WxPayData wxPayData = gson.fromJson(element, WxPayData.class);
                IWXAPI api = WXAPIFactory.createWXAPI(SendMapActivity.this, AppConst.WEIXIN_APP_ID);
                api.registerApp(AppConst.WEIXIN_APP_ID);
                PayReq payReq = new PayReq();
                payReq.appId = AppConst.WEIXIN_APP_ID;
                payReq.partnerId = wxPayData.getPartnerid();
                payReq.prepayId = wxPayData.getPrepayid();
                payReq.packageValue = "Sign=WXPay";
                payReq.nonceStr = wxPayData.getNoncestr();
                payReq.timeStamp = "" + wxPayData.getTimestamp();
                payReq.sign = wxPayData.getSign();
                AppConst.ORDER_TYPE = 2;
                api.sendReq(payReq);
            }

            @Override
            public void onFailure(int statusCode, String errorMsg) {
                LogUtil.i(errorMsg + "statusCode" + statusCode);
                showToast(errorMsg);
                mProgressDialog.dismiss();
            }
        });
    }

    private void getMoney() {

        Map<String, String> map = new HashMap<>();
        map.put("uid", uid + "");
        map.put("token", StringUtil.getToken(uid));
        //  mProgressDialog.show();
        OkHttpUtil.getInstance().post(this, AppConst.URL_GET_MONEY, map, new IResponse() {
            @Override
            public void onSuccess(JsonElement element) {
                // mProgressDialog.dismiss();
                LogUtil.i(element.toString());
                Gson gson = new Gson();
                String result = element.toString().replace("null", "\"\"");
                BalanceInfo balanceInfo = gson.fromJson(result, BalanceInfo.class);
                myMoney = balanceInfo.getBalance();

                SPUtil.put(SendMapActivity.this, "withdraw", myMoney);
                // mTvMineMoney.setText("¥" + money);
            }

            @Override
            public void onFailure(int statusCode, String errorMsg) {
                LogUtil.i(errorMsg + "statusCode" + statusCode);
                myMoney = SPUtil.getString(SendMapActivity.this, "withdraw");
                //  mProgressDialog.dismiss();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 50 && resultCode == RESULT_OK) {
            String path = FileUtil.PATH + "map.png";
            mMapView.setImageBitmap(FileUtil.getLoacalBitmap(path));
            curLatLng = data.getParcelableExtra("curLatLng");
            address = data.getStringExtra("address");
            LogUtil.i("address" + address);
            LogUtil.i("latitude" + curLatLng.latitude);
            LogUtil.i("longitude" + curLatLng.longitude);
        }
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            //添加图片返回
            if (data != null && requestCode == 100) {
                ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                path = images.get(0).path;
                Glide
                        .with(SendMapActivity.this)
                        .load(images.get(0).path)
                        .skipMemoryCache(true)
                        .into(ivUp);
            }
        }

    }

    class MyBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //写入接收广播后的操作
            payDialog.dismiss();
            finish();
        }
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        spinnerInfo = (SpinnerInfo) spinnerAdapter.getItem(position);
        getPacketNum();
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }


    private void getBankArea() {
        Map<String, String> map = new HashMap<>();

        OkHttpUtil.getInstance().post(this, AppConst.URL_GET_BANK_AREA, map, new IResponse() {
            @Override
            public void onSuccess(JsonElement element) {
                LogUtil.i(element.toString());
                Gson gson = new Gson();
                String result = element.toString().replace("null", "\"\"");
                ArrayList<SpinnerInfo> list = gson.fromJson(result, new TypeToken<ArrayList<SpinnerInfo>>() {
                }.getType());
                spinnerAdapter.setData(list);
                spinner.setAdapter(spinnerAdapter);
//                spinnerAdapter.
            }

            @Override
            public void onFailure(int statusCode, String errorMsg) {
                LogUtil.i(errorMsg + "statusCode" + statusCode);
                showToast(errorMsg);
            }
        });
    }

    private void getPacketNum() {
        double ss = 0;
        try {
            ss = Double.parseDouble(mEtMoney.getText().toString());
        } catch (Exception e) {

        }
        if (ss <= 0) {
            return;
        }
        Map<String, String> map = new HashMap<>();
        map.put("packet_money", mEtMoney.getText().toString());
        map.put("packet_level", spinnerInfo.level);
        OkHttpUtil.getInstance().post(this, AppConst.URL_PACKET_NUM, map, new IResponse() {
            @Override
            public void onSuccess(JsonElement element) {
                LogUtil.i(element.toString());
                Gson gson = new Gson();
                String result = element.toString().replace("null", "\"\"");
                info = gson.fromJson(result, Packet_numInfo.class);
                mEtAmount.setText(info.suggest);
            }

            @Override
            public void onFailure(int statusCode, String errorMsg) {
                LogUtil.i(errorMsg + "statusCode" + statusCode);
                showToast(errorMsg);
            }
        });
    }
}
